package com.attendance.www.hr.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import com.attendance.www.hr.beans.EmployeeBean;
import com.attendance.www.hr.beans.EmployeePageBean;
import com.attendance.www.hr.beans.RoleBean;
import com.attendance.www.hr.constant.AppConstant;
import com.attendance.www.hr.dao.mapper.ApprovalRecordMapper;
import com.attendance.www.hr.dao.mapper.AttachmentMapper;
import com.attendance.www.hr.dao.mapper.AttendanceMapper;
import com.attendance.www.hr.dao.mapper.AttendanceReportExtMapper;
import com.attendance.www.hr.dao.mapper.AttendanceReportMapper;
import com.attendance.www.hr.dao.mapper.DepartmentMapper;
import com.attendance.www.hr.dao.mapper.EmployeeCorporationMapper;
import com.attendance.www.hr.dao.mapper.EmployeeDepartmentMapper;
import com.attendance.www.hr.dao.mapper.EmployeeExtMapper;
import com.attendance.www.hr.dao.mapper.EmployeeMapper;
import com.attendance.www.hr.dao.mapper.EmployeeRoleMapper;
import com.attendance.www.hr.dao.mapper.EmployeeSchedulMapper;
import com.attendance.www.hr.dao.mapper.FurloughBalanceMapper;
import com.attendance.www.hr.dao.mapper.PunchTimeMapper;
import com.attendance.www.hr.dao.mapper.RequestMapper;
import com.attendance.www.hr.dao.mapper.RetroactiveMapper;
import com.attendance.www.hr.dao.mapper.RoleDepartmentMapper;
import com.attendance.www.hr.dao.mapper.RoleMapper;
import com.attendance.www.hr.dao.mapper.SchedulDayMapper;
import com.attendance.www.hr.dao.mapper.SchedulWeekMapper;
import com.attendance.www.hr.dao.mapper.SystemConfigureMapper;
import com.attendance.www.hr.dao.mapper.TaskMapper;
import com.attendance.www.hr.dao.mapper.UserMapper;
import com.attendance.www.hr.entitys.ApprovalRecord;
import com.attendance.www.hr.entitys.ApprovalRecordExample;
import com.attendance.www.hr.entitys.Attachment;
import com.attendance.www.hr.entitys.Attendance;
import com.attendance.www.hr.entitys.AttendanceExample;
import com.attendance.www.hr.entitys.AttendanceReport;
import com.attendance.www.hr.entitys.AttendanceReportExample;
import com.attendance.www.hr.entitys.Department;
import com.attendance.www.hr.entitys.Employee;
import com.attendance.www.hr.entitys.EmployeeCorporation;
import com.attendance.www.hr.entitys.EmployeeCorporationExample;
import com.attendance.www.hr.entitys.EmployeeDepartment;
import com.attendance.www.hr.entitys.EmployeeDepartmentExample;
import com.attendance.www.hr.entitys.EmployeeExample;
import com.attendance.www.hr.entitys.EmployeeExample.Criteria;
import com.attendance.www.hr.entitys.EmployeeRole;
import com.attendance.www.hr.entitys.EmployeeRoleExample;
import com.attendance.www.hr.entitys.EmployeeSchedul;
import com.attendance.www.hr.entitys.EmployeeSchedulExample;
import com.attendance.www.hr.entitys.FurloughBalance;
import com.attendance.www.hr.entitys.FurloughBalanceExample;
import com.attendance.www.hr.entitys.PunchTime;
import com.attendance.www.hr.entitys.PunchTimeExample;
import com.attendance.www.hr.entitys.Retroactive;
import com.attendance.www.hr.entitys.RetroactiveExample;
import com.attendance.www.hr.entitys.Role;
import com.attendance.www.hr.entitys.RoleDepartment;
import com.attendance.www.hr.entitys.RoleDepartmentExample;
import com.attendance.www.hr.entitys.SchedulWeek;
import com.attendance.www.hr.entitys.SchedulWeekExample;
import com.attendance.www.hr.entitys.SystemConfigure;
import com.attendance.www.hr.entitys.SystemConfigureExample;
import com.attendance.www.hr.entitys.User;
import com.attendance.www.hr.entitys.UserExample;
import com.attendance.www.hr.exception.ResultFaultException;
import com.attendance.www.hr.service.IApprovalService;
import com.attendance.www.hr.service.IEmployeeService;
import com.attendance.www.hr.service.IRestVacationService;
import com.attendance.www.hr.utils.YearFurloughUtils;
import com.zhangkongli.frame.utils.MD5Util;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

	@Resource
	private EmployeeExtMapper employeeExtDao;
	@Resource
	private EmployeeMapper employeeDao;
	@Resource
	private SchedulDayMapper schedulDayDao;
	@Resource
	private EmployeeCorporationMapper employeeCorporationDao;
	@Resource
	private EmployeeDepartmentMapper employeeDepartmentDao;
	@Resource
	private EmployeeRoleMapper employeeRoleDao;
	@Resource
	private PunchTimeMapper punchTimeDao;
	@Resource
	private SchedulWeekMapper schedulWeekDao;
	@Resource
	private EmployeeSchedulMapper employeeSchedulDao;
	@Resource
	private UserMapper userDao;
	@Resource
	private RoleMapper roleDao;
	@Resource
	private DepartmentMapper departmentDao;
	@Resource
	private RoleDepartmentMapper roleDepartmentDao;
	@Resource
	private AttendanceMapper attendanceDao;
	@Resource
	private RequestMapper requestDao;
	@Resource
	private RetroactiveMapper retroactiveDao;
	@Resource
	private ApprovalRecordMapper approvalRecordDao;
	@Resource
	private AttachmentMapper attachmentDao;
	@Resource
	private IRestVacationService restVacationService;
	@Resource
	private SystemConfigureMapper systemConfigureDao;
	@Resource
	private FurloughBalanceMapper furloughBalanceDao;
	@Resource
	private IApprovalService approvalService;
	@Resource
	private AttendanceReportMapper attendanceReportDao;
	@Resource
	private AttendanceReportExtMapper attendanceReportExtDao;
	@Resource
	private TaskMapper taskDao;

	/**
	 * 获取全部员工
	 * 
	 * @param employeeBean
	 * @param startNum
	 * @param pageCount
	 * @return
	 */
	@Override
	public EmployeePageBean getEmployeePageList(EmployeeBean employeeBean, Integer startNum, Integer pageCount) {
		EmployeePageBean epb = new EmployeePageBean();
		List<EmployeeBean> employeePageList = employeeExtDao.getEmployeePageList(employeeBean, startNum, pageCount);
		List<EmployeeBean> employeePageNewList = new ArrayList<>();
		// 通过人员ID查对应的roleList，多岗位
		for (EmployeeBean employeeBean2 : employeePageList) {
			EmployeeRoleExample employeeRoleExample = new EmployeeRoleExample();
			employeeRoleExample.createCriteria().andEmployeeIdEqualTo(employeeBean2.getEmployeeId());
			employeeRoleExample.setOrderByClause("is_role desc");
			List<EmployeeRole> employeeRoleList = employeeRoleDao.selectByExample(employeeRoleExample);
			List<RoleBean> roleBeanList = new ArrayList<>();
			// 查询岗位信息by Id
			for (EmployeeRole employeeRole : employeeRoleList) {
				// 每个人对应的岗位，循环
				Role role = roleDao.selectByPrimaryKey(employeeRole.getRoleId());
				
				//查询岗位对应部门
				RoleDepartmentExample roleDepartmentExample=new RoleDepartmentExample();
				roleDepartmentExample.createCriteria().andRoleIdEqualTo(role.getRoleId());
				List<RoleDepartment> roleDepartmentList=roleDepartmentDao.selectByExample(roleDepartmentExample);
				Department department=null;
				if(roleDepartmentList.size()>0) {
					// 查岗位对应的部门
					department=departmentDao.selectByPrimaryKey(roleDepartmentList.get(0).getDepartmentId());
				}				
				if (role.getIsDisabled() != 1) {
					// 导入岗位bean
					RoleBean roleBean = new RoleBean();
					roleBean.setDescription(role.getDescription());
					roleBean.setParentId(role.getParentId());
					roleBean.setRoleCode(role.getRoleCode());
					roleBean.setRoleId(role.getRoleId());
					roleBean.setRoleLevel(role.getRoleLevel());
					roleBean.setRoleName(role.getRoleName());
					roleBean.setIsRole(employeeRole.getIsRole());
					roleBean.setFromDate(employeeRole.getFromDate());
					roleBean.setThruDate(employeeRole.getThruDate());
					if (department!=null) {
						roleBean.setDepartmentName(department.getDepartmentName());
						roleBean.setDepartmentCode(department.getDepartmentCode());
					}
					roleBeanList.add(roleBean);
				}
				employeeBean2.setRoleList(roleBeanList);
			}
			employeePageNewList.add(employeeBean2);
		}
		epb.setEmployeeBeanList(employeePageNewList);
		epb.setPageTotal(employeeExtDao.getEmployeeSum(employeeBean));
		return epb;
	}

	/**
	 * 获取全部员工ID集合
	 * 
	 * @param employeeNo
	 * @param roleName
	 * @param departmentName
	 * @param employeeIsSeparated
	 * @return
	 */
	@Override
	public List<Integer> getEmployeeIdList(String employeeNo, String roleName, String departmentName,
			String corporationName, Integer employeeIsSeparated) {
		return employeeExtDao.getEmployeeIdList(employeeNo, roleName, departmentName, corporationName,
				employeeIsSeparated);
	}

	/**
	 * 修改免签人员
	 */
	@Override
	public boolean updateVisaWaiver(EmployeeBean employeeBean) {
		List<Integer> employeeIdList = employeeBean.getEmployeeIdList();
		Boolean isType = employeeBean.getIsType();
		EmployeeExample employeeExample = new EmployeeExample();
		employeeExample.createCriteria().andEmployeeIsSeparatedEqualTo(0).andEmployeeIdIn(employeeIdList);
		Employee employee = new Employee();
		employee.setUpdateTime(new Date());
		if (isType) {
			employee.setIsVisaWaiver(1);
		} else {
			employee.setIsVisaWaiver(0);
		}
		int record = employeeDao.updateByExampleSelective(employee, employeeExample);
		if (record > 0) {
			return true;
		}
		return false;
	}

	/**
	 * 查询员工级别
	 */
	@Override
	public List<Integer> getLevelList() {
		return employeeExtDao.getLevelList();
	}

	/**
	 * 新增员工
	 */
	@Override
	public boolean saveEmployee(EmployeeBean employeeBean) {
		Employee employee = new Employee();
		String employeeNo = employeeBean.getEmployeeNo();
		String email = employeeBean.getEmail();
		// 获取默认状态下的考勤打卡Id
		PunchTimeExample punchTimeExample = new PunchTimeExample();
		punchTimeExample.createCriteria().andIsDefaultEqualTo(1);
		List<PunchTime> punchTimeList = punchTimeDao.selectByExample(punchTimeExample);
		int punchTimeId = punchTimeList.get(0).getPunchTimeId();
		// 获取默认状态下的班次表Id
		SchedulWeekExample schedulWeekExample = new SchedulWeekExample();
		schedulWeekExample.createCriteria().andIsDefaultEqualTo(1);
		List<SchedulWeek> schedulWeekList = schedulWeekDao.selectByExample(schedulWeekExample);
		int swId = schedulWeekList.get(0).getSwId();

		employee.setEmployeeNo(employeeNo);
		employee.setChineseName(employeeBean.getChineseName());
		employee.setEnglishName(employeeBean.getEnglishName());
		employee.setSex(employeeBean.getSex());
		employee.setEmail(email);
		employee.setAnnualLeaveDate(employeeBean.getAnnualLeaveDate());
		employee.setFirstDate(employeeBean.getFirstDate());
		employee.setEntryDate(employeeBean.getEntryDate());
		employee.setEmployeeType(employeeBean.getEmployeeType());
		employee.setEmployeeCategory(employeeBean.getEmployeeCategory());
		employee.setLevel(employeeBean.getLevel());
		employee.setRegionType(employeeBean.getRegionType());
		employee.setFromDate(employeeBean.getEntryDate());//员工开始时间定为==入职时间
		employee.setThruDate(employeeBean.getThruDate());
		int record = employeeDao.insertSelective(employee);
		if (record <= 0) {
			return false;
		}
		int employeeId = employee.getEmployeeId();

		// 给员工分配到默认班次
		EmployeeSchedul employeeSchedul = new EmployeeSchedul();
		employeeSchedul.setEmployeeId(employeeId);
		employeeSchedul.setSwId(swId);
		employeeSchedul.setPunchTimeId(punchTimeId);
		employeeSchedul.setFromDate(employeeBean.getEntryDate());
		employeeSchedul.setThruDate(schedulWeekList.get(0).getThruDate());
		record = employeeSchedulDao.insertSelective(employeeSchedul);
		if (record <= 0) {
			return false;
		}
		// 员工公司表
		EmployeeCorporation employeeCorporation = new EmployeeCorporation();
		employeeCorporation.setCorporationId(employeeBean.getCorporationId());
		employeeCorporation.setEmployeeId(employeeId);
		employeeCorporation.setFromDate(employeeBean.getCorporationFromDate());
		employeeCorporation.setThruDate(employeeBean.getCorporationThruDate());
		employeeCorporation.setIsCorporation(0);// 此表0表示是默认公司，新增时需手动插入
		record = employeeCorporationDao.insertSelective(employeeCorporation);
		if (record <= 0) {
			return false;
		}
		// 员工部门表
		if (employeeBean.getDepartmentId() != null) {
			EmployeeDepartment employeeDepartment = new EmployeeDepartment();
			employeeDepartment.setEmployeeId(employeeId);
			employeeDepartment.setDepartmentId(employeeBean.getDepartmentId());
			employeeDepartment.setFromDate(employeeBean.getDepartmentFromDate());
			employeeDepartment.setThruDate(employeeBean.getDepartmentThruDate());
			record = employeeDepartmentDao.insertSelective(employeeDepartment);
			if (record <= 0) {
				return false;
			}
		}
		// 员工岗位表，插入多岗位
		if (employeeBean.getRoleList() != null && employeeBean.getRoleList().size() > 0) {
			List<RoleBean> roleBeanList = employeeBean.getRoleList();
			EmployeeRole employeeRole = new EmployeeRole();
			employeeRole.setEmployeeId(employeeId);
			for (RoleBean roleBean : roleBeanList) {
				employeeRole.setRoleId(roleBean.getRoleId());
				employeeRole.setFromDate(roleBean.getFromDate());
				employeeRole.setThruDate(roleBean.getThruDate());
				employeeRole.setIsRole(roleBean.getIsRole());
				record = employeeRoleDao.insertSelective(employeeRole);
				if (record <= 0) {
					return false;
				}
			}
		}
		// user用户表
		User user = new User();
		user.setEmployeeId(employeeId);
		MD5Util md5 = new MD5Util();
		String mdPassWord = md5.getMD5ofStr(AppConstant.PASSWORD);
		user.setPassword(mdPassWord);
		user.setPrivilegeGroupId(employeeBean.getPrivilegeGroupId());
		user.setUsername(employeeBean.getUserName());
		user.setFromDate(employeeBean.getEntryDate());//user开始时间定为==入职时间
		record = userDao.insertSelective(user);
		if (record <= 0) {
			return false;
		}

		return true;
	}

	/**
	 * 离职员工
	 */
	@Override
	public boolean deleteEmployee(EmployeeBean employeeBean) {
		Employee employee = new Employee();
		int employeeId = employeeBean.getEmployeeId();
		Date lastDate = employeeBean.getEmployeeSeparatedDate();
		employee.setEmployeeId(employeeId);
		employee.setEmployeeIsSeparated(1);
		employee.setEmployeeSeparatedDate(lastDate);
		int record = employeeDao.updateByPrimaryKeySelective(employee);
		if (record <= 0) {
			return false;
		}
		
		// 逻辑删除排班
		EmployeeSchedulExample example = new EmployeeSchedulExample();
		example.createCriteria().andEmployeeIdEqualTo(employeeId)
		.andThruDateGreaterThan(lastDate);
		EmployeeSchedul employeeSchedul = new EmployeeSchedul();
		employeeSchedul.setThruDate(lastDate);
		employeeSchedulDao.updateByExampleSelective(employeeSchedul, example);
		
		//删除考勤信息
		AttendanceExample attendanceExample=new AttendanceExample();
		attendanceExample.createCriteria().andEmployeeIdEqualTo(employeeId)
		.andAttendanceDateGreaterThan(lastDate);
		List<Attendance> attendanceList=attendanceDao.selectByExample(attendanceExample);
		for(int i=0;i<attendanceList.size();i++){
			//删除考勤表信息
			Integer attendanceId=attendanceList.get(i).getAttendanceId();
			attendanceDao.deleteByPrimaryKey(attendanceId);

			RetroactiveExample retroactiveExample=new RetroactiveExample();
			retroactiveExample.createCriteria().andAttendanceIdEqualTo(attendanceId);
			List<Retroactive> retroactiveList=retroactiveDao.selectByExample(retroactiveExample);
			for(int j=0;j<retroactiveList.size();j++){
				Integer retroactiveId=retroactiveList.get(j).getRetroactiveId();
				//删除补签审批步骤信息
				ApprovalRecordExample approvalRecordExample=new ApprovalRecordExample();
				approvalRecordExample.createCriteria()
				.andRetroactiveIdEqualTo(retroactiveId);
				approvalRecordDao.deleteByExample(approvalRecordExample);
				//删除删除补签表信息
				retroactiveDao.deleteByPrimaryKey(retroactiveId);
			}
		}
		//设置人员公司表结束时间
		EmployeeCorporationExample ecExample = new EmployeeCorporationExample();
		ecExample.or().andEmployeeIdEqualTo(employeeId).andThruDateIsNull();
		ecExample.or().andEmployeeIdEqualTo(employeeId).andThruDateGreaterThan(lastDate);
		EmployeeCorporation ec = new EmployeeCorporation();
		ec.setThruDate(lastDate);
		employeeCorporationDao.updateByExampleSelective(ec, ecExample);
		
		//设置人员部门表结束时间
		EmployeeDepartmentExample edExample = new EmployeeDepartmentExample();
		edExample.or().andEmployeeIdEqualTo(employeeId).andThruDateIsNull();
		edExample.or().andEmployeeIdEqualTo(employeeId).andThruDateGreaterThan(lastDate);
		EmployeeDepartment ed = new EmployeeDepartment();
		ed.setThruDate(lastDate);
		employeeDepartmentDao.updateByExampleSelective(ed, edExample);
		
		//查询员工的有效岗位
		EmployeeRoleExample erExample = new EmployeeRoleExample();
		erExample.or().andEmployeeIdEqualTo(employeeId).andThruDateIsNull();
		erExample.or().andEmployeeIdEqualTo(employeeId).andThruDateGreaterThan(lastDate);
		List<EmployeeRole> erList = employeeRoleDao.selectByExample(erExample);
		
		//设置人员岗位表结束时间
		EmployeeRole er = new EmployeeRole();
		er.setThruDate(lastDate);
		employeeRoleDao.updateByExampleSelective(er, erExample);
		
		//待审批的找N+1
		for (EmployeeRole employeeRole : erList) {
			if (employeeBean.getFindN()==1) {
				//验证是否是空岗，然后让待审批的找N+1
				this.checkEmptyRole(employeeRole.getRoleId(), employeeId);
			}
		}
		//更新离职人员的报表数据的离职日期
		AttendanceReportExample arExample = new AttendanceReportExample();
		arExample.createCriteria().andEmployeeIdEqualTo(employeeId);
		AttendanceReport att = new AttendanceReport();
		att.setEmployeeSeparatedDate(lastDate);
		attendanceReportDao.updateByExampleSelective(att, arExample);
		//离职后
		//delete大于离职日期的数据
		AttendanceReportExample arExampleDel = new AttendanceReportExample();
		arExampleDel.createCriteria().andEmployeeIdEqualTo(employeeId)
		.andAttendanceReportDateGreaterThan(lastDate);
		attendanceReportDao.deleteByExample(arExampleDel);
		
		//插入任务表数据
		/*approvalService.insertTaskByParam(lastDate, employeeId);
		//查询报表数据的最后一天日期，和离职日期比较
		Date theDay = attendanceReportExtDao.getTheDay(employeeId);
		while (lastDate.after(theDay)) {
			//判断，插入数据
			approvalService.insertTaskByParam(lastDate, employeeId);
			
			lastDate = DateUtils.addDays(lastDate, -1);
		}*/
		
		return true;
	}

	/**
	 * 验证是否是空岗，然后让待审批的找N+1
	 * @param roleId
	 */
	private void checkEmptyRole (Integer roleId, Integer employeeId) {
		//查询验证
		EmployeeRoleExample checkExample = new EmployeeRoleExample();
		checkExample.or().andRoleIdEqualTo(roleId)
		.andFromDateLessThanOrEqualTo(new Date())
		.andThruDateIsNull()
		.andEmployeeIdNotEqualTo(employeeId);
		checkExample.or().andRoleIdEqualTo(roleId)
		.andFromDateLessThanOrEqualTo(new Date())
		.andThruDateGreaterThanOrEqualTo(new Date())
		.andEmployeeIdNotEqualTo(employeeId);
		List<EmployeeRole> checkList = employeeRoleDao.selectByExample(checkExample);
		if (checkList.size()==0) {
//			throw new ResultFaultException("19_00001");
			//待审批的申请找N+1
			ApprovalRecordExample arExample = new ApprovalRecordExample();
			arExample.createCriteria().andRoleIdEqualTo(roleId)
			.andIsApproveEqualTo(1);
			List<ApprovalRecord> arList = approvalRecordDao.selectByExample(arExample);
			for (ApprovalRecord approvalRecord : arList) {
				//审批人岗位role
				Role approvalRole = roleDao.selectByPrimaryKey(roleId);
				//N+1，就是父级id
				approvalRecord.setRoleId(approvalRole.getParentId());
				approvalRecord.setUpdateTime(new Date());//设置更新时间
				approvalRecordDao.updateByPrimaryKeySelective(approvalRecord);
			}
		}

		//复杂算法，先注释掉
		/*for (ApprovalRecord approvalRecord : arList) {
			//申请和补签
			if (approvalRecord.getRequestId()!=null) {
				//根据requestId查审批信息，找到下一个审批人
				//查所有审批信息
				List<ApprovalRecordBean> arbList = approvalService.getApprovalRecordInfoById(approvalRecord.getRequestId().toString());
				for (int i = 0; i < arbList.size(); i++) {
					if (arbList.get(i).getRoleId()==roleId) {
						//下一个审批人roleId
						Integer nextRoleId = arbList.get(i+1).getRoleId();
						approvalRecord.setRoleId(nextRoleId);
						//两个time设置为null
						approvalRecord.setCreateTime(null);
						approvalRecord.setUpdateTime(null);
						approvalRecordDao.updateByPrimaryKeySelective(approvalRecord);
					}
				}
			} else if (approvalRecord.getRetroactiveId()!=null){//补签
				//补签，找父级岗位，update
				//审批人岗位role
				Role approvalRole = roleDao.selectByPrimaryKey(roleId);
				Role nextRole = approvalService.getNextApprovalRoleId(approvalRole, 99, null);
				approvalRecord.setRoleId(nextRole.getRoleId());
				approvalRecordDao.updateByPrimaryKeySelective(approvalRecord);
			}
		}*/
	}
	
	/**
	 * 修改员工
	 */
	@Override
	public boolean updateEmployee(EmployeeBean employeeBean) {
		// 更新验证updatetime
		int employeeId = employeeBean.getEmployeeId();
		Employee employeeDB = employeeDao.selectByPrimaryKey(employeeId);
		if (!employeeDB.getUpdateTime().equals(employeeBean.getUpdateTime())) {
			throw new ResultFaultException("0_00011");
		}
		String employeeNo = employeeBean.getEmployeeNo();
		String email = employeeBean.getEmail();
		employeeDB.setEmployeeNo(employeeNo);
		employeeDB.setAnnualLeaveDate(employeeBean.getAnnualLeaveDate());
		employeeDB.setChineseName(employeeBean.getChineseName());
		employeeDB.setEnglishName(employeeBean.getEnglishName());
		employeeDB.setSex(employeeBean.getSex());
		employeeDB.setEmail(email);
		//如果修改了首次工作时间，进行判断，进而修改年假余额
		if (!employeeDB.getFirstDate().equals(employeeBean.getFirstDate())) {
			
			//去年的开始时间、结束时间
			Calendar lastCalendarBegin = Calendar.getInstance();
			lastCalendarBegin.setTime(new Date());
			lastCalendarBegin.add(Calendar.YEAR, -1);
			Date lastBeginDate=lastCalendarBegin.getTime();
			
			//系统配置表
			List<SystemConfigure>  scList=systemConfigureDao.selectByExample(new SystemConfigureExample());
			//修改前的年假天数
			Float yearFurloughFloat = YearFurloughUtils.getYearFurloughHours(employeeDB.getFirstDate(), employeeDB.getEntryDate(), new Date(), scList) * 8 * 60;
			yearFurloughFloat=(float) Math.round(yearFurloughFloat);
			//去年年假，分钟数
			Float lastYearFurloughFloat = YearFurloughUtils.getYearFurloughHours(employeeDB.getFirstDate(), employeeDB.getEntryDate(), lastBeginDate, scList) * 8 * 60;
			lastYearFurloughFloat=(float) Math.round(lastYearFurloughFloat);
			
			//修改后的年假天数
			Float afterYearFurloughFloat = YearFurloughUtils.getYearFurloughHours(employeeBean.getFirstDate(), employeeBean.getEntryDate(), new Date(), scList) * 8 * 60;
			afterYearFurloughFloat=(float) Math.round(afterYearFurloughFloat);
			//修改后  去年年假，分钟数
			Float afterLastYearFurloughFloat = YearFurloughUtils.getYearFurloughHours(employeeBean.getFirstDate(), employeeBean.getEntryDate(), lastBeginDate, scList) * 8 * 60;
			afterLastYearFurloughFloat=(float) Math.round(afterLastYearFurloughFloat);
			
			//如果年假天数不等 
			if (!yearFurloughFloat.equals(afterYearFurloughFloat)) {
				Calendar cal = Calendar.getInstance();
				cal.setTime(new Date());
				int year=cal.get(Calendar.YEAR);
				FurloughBalanceExample furloughBalanceExample = new FurloughBalanceExample();
				furloughBalanceExample.createCriteria().andFurloughBalanceTypeEqualTo(1)
				.andEmployeeIdEqualTo(employeeId)
				.andYearEqualTo(year+"");
				List<FurloughBalance> furloughBalanceList= furloughBalanceDao.selectByExample(furloughBalanceExample);
				if (furloughBalanceList.size()>0) {
					FurloughBalance furloughBalance = furloughBalanceList.get(0);
//					BigDecimal initHoursDay = furloughBalance.getInitHoursDay();//init可能是Null
					BigDecimal initHoursDay = new BigDecimal(yearFurloughFloat.toString());
					BigDecimal afterInitHoursDay = new BigDecimal(afterYearFurloughFloat.toString());
					BigDecimal balanceHoursDay = furloughBalance.getBalanceHoursDay();
					BigDecimal afterBalanceHoursDay = balanceHoursDay.add(afterInitHoursDay.subtract(initHoursDay));
					
					furloughBalance.setBalanceHoursDay(afterBalanceHoursDay);
					furloughBalance.setInitHoursDay(afterInitHoursDay);
					furloughBalanceDao.updateByPrimaryKeySelective(furloughBalance);
				}
			}
			
			if (!lastYearFurloughFloat.equals(afterLastYearFurloughFloat)) {
				Calendar cal = Calendar.getInstance();
				cal.setTime(new Date());
				int year=cal.get(Calendar.YEAR) - 1;
				FurloughBalanceExample furloughBalanceExample = new FurloughBalanceExample();
				furloughBalanceExample.createCriteria().andFurloughBalanceTypeEqualTo(1)
				.andEmployeeIdEqualTo(employeeId)
				.andYearEqualTo(year+"");
				List<FurloughBalance> furloughBalanceList= furloughBalanceDao.selectByExample(furloughBalanceExample);
				if (furloughBalanceList.size()>0) {
					FurloughBalance furloughBalance = furloughBalanceList.get(0);
					BigDecimal initHoursDay = new BigDecimal(lastYearFurloughFloat.toString());
					BigDecimal afterInitHoursDay = new BigDecimal(afterLastYearFurloughFloat.toString());
					BigDecimal balanceHoursDay = furloughBalance.getBalanceHoursDay();
					BigDecimal afterBalanceHoursDay = balanceHoursDay.add(afterInitHoursDay.subtract(initHoursDay));
					
					furloughBalance.setBalanceHoursDay(afterBalanceHoursDay);
					furloughBalance.setInitHoursDay(afterInitHoursDay);
					furloughBalanceDao.updateByPrimaryKeySelective(furloughBalance);
				}
			}
		}
		employeeDB.setFirstDate(employeeBean.getFirstDate());
		employeeDB.setEntryDate(employeeBean.getEntryDate());
		employeeDB.setEmployeeType(employeeBean.getEmployeeType());
		employeeDB.setEmployeeCategory(employeeBean.getEmployeeCategory());
		employeeDB.setLevel(employeeBean.getLevel());
		employeeDB.setRegionType(employeeBean.getRegionType());
		employeeDB.setEmployeeIsSeparated(employeeBean.getEmployeeIsSeparated());
		employeeDB.setUpdateTime(new Date());
		int record = employeeDao.updateByPrimaryKey(employeeDB);
		if (record <= 0) {
			return false;
		}

		// 员工公司表
		// 先删除--有日期的
		EmployeeCorporationExample employeeCorporationExample = new EmployeeCorporationExample();
		employeeCorporationExample.createCriteria().andEmployeeIdEqualTo(employeeId).andIsCorporationEqualTo(0);
		employeeCorporationDao.deleteByExample(employeeCorporationExample);
		// 再添加
		EmployeeCorporation employeeCorporation = new EmployeeCorporation();
		employeeCorporation.setCorporationId(employeeBean.getCorporationId());
		employeeCorporation.setEmployeeId(employeeId);
		employeeCorporation.setFromDate(employeeBean.getCorporationFromDate());
		employeeCorporation.setThruDate(employeeBean.getCorporationThruDate());
		employeeCorporation.setIsCorporation(0);// 此表0表示是默认公司，需手动插入
		record = employeeCorporationDao.insertSelective(employeeCorporation);
		if (record <= 0) {
			return false;
		}
		// 员工部门表
		if (employeeBean.getDepartmentId() != null) {
			// 先删除
			EmployeeDepartmentExample employeeDepartmentExample = new EmployeeDepartmentExample();
			employeeDepartmentExample.createCriteria().andEmployeeIdEqualTo(employeeId);
			employeeDepartmentDao.deleteByExample(employeeDepartmentExample);
			// 再添加
			EmployeeDepartment employeeDepartment = new EmployeeDepartment();
			employeeDepartment.setEmployeeId(employeeId);
			employeeDepartment.setDepartmentId(employeeBean.getDepartmentId());
			employeeDepartment.setFromDate(employeeBean.getDepartmentFromDate());
			employeeDepartment.setThruDate(employeeBean.getDepartmentThruDate());
			record = employeeDepartmentDao.insertSelective(employeeDepartment);
			if (record <= 0) {
				return false;
			}
		}
		
		//岗位变化
		//原岗位信息
		EmployeeRoleExample erExample = new EmployeeRoleExample();
		erExample.createCriteria().andEmployeeIdEqualTo(employeeId);
		List<EmployeeRole> erListDB = employeeRoleDao.selectByExample(erExample);
		//现在的岗位信息
		List<RoleBean> roleBeanList = employeeBean.getRoleList();
		//是否有岗位变化
		boolean isChange = false;
		for (int i = 0; i < erListDB.size(); i++) {
			//判断是否原岗位被删除
			boolean isDel = true;
			//原岗位id
			int roleIdDB = erListDB.get(i).getRoleId();
			for (int j = 0; j < roleBeanList.size(); j++) {
				if (roleIdDB == roleBeanList.get(j).getRoleId()) {
					isDel = false;
				} 
			}
			if (isDel) {
				isChange = true;
				if (employeeBean.getFindN()==1) {
					//验证是否是空岗
					this.checkEmptyRole(roleIdDB, employeeId);
				}
			}
		}
		//如果岗位有变化(增加或减少)，则操作人员岗位表
		if (isChange || roleBeanList.size() != erListDB.size()) {
			//员工岗位表
			if (roleBeanList != null && roleBeanList.size() > 0) {
				// 先删除
				EmployeeRoleExample employeeRoleExample = new EmployeeRoleExample();
				employeeRoleExample.createCriteria().andEmployeeIdEqualTo(employeeId);
				employeeRoleDao.deleteByExample(employeeRoleExample);
				// 再添加
				EmployeeRole employeeRole = new EmployeeRole();
				employeeRole.setEmployeeId(employeeId);
				for (RoleBean roleBean : roleBeanList) {
					employeeRole.setRoleId(roleBean.getRoleId());
					employeeRole.setFromDate(roleBean.getFromDate());
					employeeRole.setThruDate(roleBean.getThruDate());
					employeeRole.setIsRole(roleBean.getIsRole());
					record = employeeRoleDao.insertSelective(employeeRole);
					if (record <= 0) {
						return false;
					}
				}
			}
		}
		UserExample userExample = new UserExample();
		userExample.createCriteria().andEmployeeIdEqualTo(employeeId);
		List<User> userList = userDao.selectByExample(userExample);
		if (userList.size() > 0) {
			// user用户表
			User user = userList.get(0);
			user.setEmployeeId(employeeId);
			user.setPrivilegeGroupId(employeeBean.getPrivilegeGroupId());
			user.setUsername(employeeBean.getUserName());
			user.setUpdateTime(new Date());
			record = userDao.updateByPrimaryKeySelective(user);
			if (record <= 0) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 通过登陆时的employeeId来获取employeeBean
	 */
	@Override
	public EmployeeBean getEmployeeBeanById(Integer employeeId, Date date) {
	    EmployeeBean employeeBean=employeeExtDao.getEmployeeByEmployeeId(employeeId, date);
		EmployeeRoleExample employeeRoleExample = new EmployeeRoleExample();
		employeeRoleExample.createCriteria().andEmployeeIdEqualTo(employeeBean.getEmployeeId());
		employeeRoleExample.setOrderByClause("is_role desc");
		List<EmployeeRole> employeeRoleList = employeeRoleDao.selectByExample(employeeRoleExample);
		List<RoleBean> roleBeanList = new ArrayList<>();
		// 查询岗位信息by Id
		for (EmployeeRole employeeRole : employeeRoleList) {
			// 每个人对应的岗位，循环
			Role role = roleDao.selectByPrimaryKey(employeeRole.getRoleId());
			//增加部门名称
			RoleDepartmentExample roleDepartmentExample=new RoleDepartmentExample();
			roleDepartmentExample.createCriteria().andRoleIdEqualTo(role.getRoleId());
			List<RoleDepartment> rdList=roleDepartmentDao.selectByExample(roleDepartmentExample);
			Department department=null;
			if (rdList.size()>0) {
				department=departmentDao.selectByPrimaryKey(rdList.get(0).getDepartmentId());
			}
			if (role.getIsDisabled() != 1) {
				// 导入岗位bean
				RoleBean roleBean = new RoleBean();
				roleBean.setDescription(role.getDescription());
				roleBean.setParentId(role.getParentId());
				roleBean.setRoleCode(role.getRoleCode());
				roleBean.setRoleId(role.getRoleId());
				roleBean.setRoleLevel(role.getRoleLevel());
				roleBean.setRoleName(role.getRoleName());
				roleBean.setIsRole(employeeRole.getIsRole());
				roleBean.setFromDate(employeeRole.getFromDate());
				roleBean.setThruDate(employeeRole.getThruDate());
				if (department!=null) {
					roleBean.setDepartmentName(department.getDepartmentName());
					roleBean.setDepartmentCode(department.getDepartmentCode());
				}
				roleBeanList.add(roleBean);
			}
			employeeBean.setRoleList(roleBeanList);
		}
//			if (employeeBean.getSwType()==2) {//月班次
//				SchedulDayExample example=new SchedulDayExample();
//				example.createCriteria().andSwIdEqualTo(employeeBean.getSwId());
//				List<SchedulDayKey> schedulDayKeyList = schedulDayDao.selectByExample(example);
//				List<Date> dateList=new ArrayList<>();
//				for (SchedulDayKey schedulDayKey : schedulDayKeyList) {
//					dateList.add(schedulDayKey.getSdDate());
//				}
//				employeeBean.setSwDateList(dateList);
//			}
		return employeeBean;
	}

	/**
	 * 重置用户密码
	 */
	@Override
	public boolean resetEmployeePassWord(Integer employeeId) {
		User user = new User();
		user.setEmployeeId(employeeId);
		MD5Util md5 = new MD5Util();
		String mdPassWord = md5.getMD5ofStr(AppConstant.PASSWORD);
		user.setPassword(mdPassWord);
		UserExample examples = new UserExample();
		examples.createCriteria().andEmployeeIdEqualTo(employeeId);
		
		int record = userDao.updateByExampleSelective(user, examples);
		if (record > 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 验证
	 */
	@Override
	public void getVerifyEmployee(EmployeeBean employeeBean) {
		String employeeNo = employeeBean.getEmployeeNo();
		String email = employeeBean.getEmail();
		String userName = employeeBean.getUserName();
		Date fromDate = employeeBean.getFromDate();//基准时间
		// employeeNo重复验证
		EmployeeExample employeeExample = new EmployeeExample();
		Criteria employCriteria = employeeExample.createCriteria();
		employCriteria.andEmployeeNoEqualTo(employeeNo);
		if (employeeBean.getEmployeeId()!=null) {
			employCriteria.andEmployeeIdNotEqualTo(employeeBean.getEmployeeId());
		}
		List<Employee> list = employeeDao.selectByExample(employeeExample);
		if (list.size() > 0) {
			throw new ResultFaultException("6_00001");
		}
		// Email重复验证 （待验证是否好使）
		if (email != null) {
			EmployeeExample employeeExample2 = new EmployeeExample();
			if (employeeBean.getEmployeeId()!=null) {
				employeeExample2.or().andEmailEqualTo(email).andFromDateLessThanOrEqualTo(fromDate)
				.andThruDateGreaterThanOrEqualTo(fromDate).andIsDisabledEqualTo(0)
				.andEmployeeIdNotEqualTo(employeeBean.getEmployeeId());;
				employeeExample2.or().andEmailEqualTo(email).andFromDateLessThanOrEqualTo(fromDate).andThruDateIsNull()
				.andIsDisabledEqualTo(0).andEmployeeIdNotEqualTo(employeeBean.getEmployeeId());
			} else {
				employeeExample2.or().andEmailEqualTo(email).andFromDateLessThanOrEqualTo(fromDate)
				.andThruDateGreaterThanOrEqualTo(fromDate).andIsDisabledEqualTo(0);
				employeeExample2.or().andEmailEqualTo(email).andFromDateLessThanOrEqualTo(fromDate).andThruDateIsNull()
				.andIsDisabledEqualTo(0);
			}
			List<Employee> list2 = employeeDao.selectByExample(employeeExample2);
			if (list2.size() > 0) {
				throw new ResultFaultException("6_00003");
			}
		}
		//账号验证
		if (userName != null) {
			UserExample userExample=new UserExample();
			if (employeeBean.getEmployeeId()!=null) {
				userExample.or().andUsernameEqualTo(userName).andFromDateLessThanOrEqualTo(fromDate)
				.andThruDateGreaterThanOrEqualTo(fromDate)
				.andEmployeeIdNotEqualTo(employeeBean.getEmployeeId());
				userExample.or().andUsernameEqualTo(userName).andFromDateLessThanOrEqualTo(fromDate).andThruDateIsNull()
				.andEmployeeIdNotEqualTo(employeeBean.getEmployeeId());
			} else{
				userExample.or().andUsernameEqualTo(userName).andFromDateLessThanOrEqualTo(fromDate)
				.andThruDateGreaterThanOrEqualTo(fromDate);
				userExample.or().andUsernameEqualTo(userName).andFromDateLessThanOrEqualTo(fromDate).andThruDateIsNull();
			}
			List<User> list2=userDao.selectByExample(userExample);
			if (list2.size() > 0) {
				throw new ResultFaultException("6_00005");
			}
		}
	}

	
	/**
	 * 离职信息导入
	 * 
	 * @param attachmentId
	 * @return
	 */
	@Override
	public List<String> importEmployeeIsSeparated(Integer attachmentId) {
		List<String> successList = new ArrayList<String>();
		// 查询附件表获取路径地址
		Attachment attachment = attachmentDao.selectByPrimaryKey(attachmentId);
		// 设置文件路径
		String pathName = attachment.getUrl().replace(AppConstant.UPLOAD_RESOURCE, AppConstant.SAVE_FILE_REPOSITORY);
		File file = new File(pathName);
		Workbook work = null;
		if (file.exists()) {
			try {
				InputStream inputStream = new FileInputStream(file);
				if (pathName.matches("^.+\\.(?i)(xls)$")) {
					work = new HSSFWorkbook(inputStream);
				} else if (pathName.matches("^.+\\.(?i)(xlsx)$")) {
					work = new XSSFWorkbook(inputStream);
				}
			} catch (Exception ex) {
				throw new ResultFaultException("0_00003");
			}
		} else {
			throw new ResultFaultException("0_00003");
		}
		if (work == null) {
			throw new ResultFaultException("0_00003");
		}

		if (work != null) {
			List<String> employeeList = addEmoloyeeIsSeparated(work);
			successList.addAll(employeeList);
		}
		return successList;
	}

	/**
	 * 增加离职信息
	 */
	@Override
	public List<String> addEmoloyeeIsSeparated(Workbook work) {

		String employeeNo = null;

		Map<Integer, Integer> employeeNoMap = new HashMap<Integer, Integer>();

		List<String> successList = new ArrayList<String>();

		Map<String, Integer> employeeMap = new HashMap<String, Integer>();
		// 获取工作表的数量
		int sheetNum = work.getNumberOfSheets();
		EmployeeExample employeeExample = new EmployeeExample();
		employeeExample.createCriteria().andEmployeeIsSeparatedEqualTo(0);
		List<Employee> employeeAllList = employeeDao.selectByExample(employeeExample);
		for (int j = 0; j < employeeAllList.size(); j++) {
			employeeMap.put(employeeAllList.get(j).getEmployeeNo(), 1);
		}

		// 遍历工作表 找出要导入的Excel表
		for (int m = 0; m < sheetNum; m++) {
			Sheet sh = work.getSheetAt(m);
			if (sh.getSheetName().equals("离职人员信息")) {
				Sheet sheet = work.getSheetAt(m);
				List<String> errorMsgList = new ArrayList<String>();// 创建错误信息列表
				// 扫描Excel每行的每个单元格
				for (int i = 1; i <= sheet.getLastRowNum(); i++) {
					Employee employee = new Employee();// 创建员工对象
					StringBuilder str = new StringBuilder("第" + (i + 1) + "行");
					Row row = sheet.getRow(i);
					// 如果一整行为空则忽略此行继续遍历
					if (row == null) {
						continue;
					}
					// 遍历某一行的所有列，如果此行每列都为空则跳过继续下一行
					boolean isNull = true;
					for (int c = 0; c < row.getLastCellNum(); c++) {
						if (row.getCell(c) == null || StringUtils.isBlank(row.getCell(c).toString())) {
							continue;
						} else {
							isNull = false;
						}
					}
					if (isNull) {
						continue;
					}
					// 判断第一列员工号的合法性
					if (row.getCell(0) != null && StringUtils.isNotBlank(row.getCell(0).toString())) {
						if (row.getCell(0).getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
							employeeNo = new BigDecimal(row.getCell(0).getNumericCellValue()).intValue() + "";
						} else {
							employeeNo = row.getCell(0).toString();
						}
						if (employeeNo.length() <= 4) {
							employeeNo = "0" + employeeNo;
						}
						if (employeeMap.containsKey(employeeNo)) {
							if (!employeeNoMap.containsKey(Integer.valueOf(employeeNo))) {
								employee.setEmployeeNo(employeeNo);
								employee.setEmployeeIsSeparated(1);
								employeeNoMap.put(Integer.valueOf(employeeNo), 1);
							} else {
								str.append("员工号重复");
							}
						}  else {
							str.append("员工号不存在");
						}
					} else {
						str.append("员工号不能为空,");
					}
					// 判断第三列离职日期的合法性
					Date leaveDate = new Date();
					if (row.getCell(2) != null && StringUtils.isNotBlank(row.getCell(2).toString())) {
						SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");// 可以方便地修改日期格式
						try {
							// 判断是否为字符串
							if (row.getCell(2).getCellType() == HSSFCell.CELL_TYPE_STRING) {
								leaveDate = dateFormat.parse(row.getCell(2).toString());
							}
							// 判断是否为日期
							else if (HSSFDateUtil.isCellDateFormatted(row.getCell(2))) {
								leaveDate = row.getCell(2).getDateCellValue();
							}
						} catch (Exception e) {
							str.append("离职时间格式不正确,");
						}
						if (leaveDate != null) {
							employee.setEmployeeSeparatedDate(leaveDate);
						} else {
							str.append("离职时间格式不正确,");
						}
					} else {
						str.append("离职日期不能为空,");
					}
					// 判断第四列是否找N+1审批
					Integer findN = null;
					if (row.getCell(3) != null && StringUtils.isNotBlank(row.getCell(3).toString())) {
						String findNStr = row.getCell(3).getStringCellValue();
						if (findNStr.equals("是")) {
							findN=1;
						} else if (findNStr.equals("否")){
							findN=0;
						}
						// 判断是否为字符串
//						if (row.getCell(3).getCellType() == HSSFCell.CELL_TYPE_STRING) {
//						}
					}
//					else {
//						str.append("离职日期不能为空,");
//					}
					
					if (str.length() == new String("第" + (i + 1) + "行").length()) {
						EmployeeBean employeeBean = new EmployeeBean();
						if (findN==null) {
							employeeBean.setFindN(0);
						} else {
							employeeBean.setFindN(findN);
						}
						employeeBean.setEmployeeSeparatedDate(leaveDate);
						//查询人员id
						EmployeeExample empExample = new EmployeeExample();
						empExample.or().andEmployeeNoEqualTo(employeeNo)
						.andFromDateLessThanOrEqualTo(new Date())
						.andThruDateIsNull();
						empExample.or().andEmployeeNoEqualTo(employeeNo)
						.andFromDateLessThanOrEqualTo(new Date())
						.andThruDateGreaterThanOrEqualTo(new Date());
						
						List<Employee> empList = employeeDao.selectByExample(empExample);
						if (empList.size()>0) {
							Integer employeeId = empList.get(0).getEmployeeId();
							employeeBean.setEmployeeId(employeeId);
							//离职操作
							this.deleteEmployee(employeeBean);
						}
//						EmployeeExample employeeExample2 = new EmployeeExample();
//						employeeExample2.createCriteria().andEmployeeNoEqualTo(employee.getEmployeeNo());
//						employeeDao.updateByExampleSelective(employee, employeeExample2);//国庆写法
					} else {
						String errorStr = str.toString().substring(0, str.toString().length());
						errorMsgList.add(errorStr);
					}
				}
				if (errorMsgList.size() > 0) {
					throw new ResultFaultException("13_00001", errorMsgList);
				}

				successList.add(0, "离职员工信息导入完成。");
				return successList;
			}
		}
		throw new ResultFaultException("13_00001");
	}

	/**
	 * 撤回离职人员
	 */
	@Override
	public boolean updateEmployeeByRevocation(EmployeeBean employeeBean) {
		// TODO Auto-generated method stub
		Employee employee = new Employee();
		int employeeId = employeeBean.getEmployeeId();
		
		employee = employeeDao.selectByPrimaryKey(employeeId);
		//离职日期
		Date lastDate = employee.getEmployeeSeparatedDate();
		
		employee.setEmployeeIsSeparated(0);
		employee.setEmployeeSeparatedDate(null);
		employee.setUpdateTime(new Date());
		//更新，null值也要更新
		int record = employeeDao.updateByPrimaryKey(employee);
		if (record <= 0) {
			return false;
		}
		
		//只能恢复默认排班
		//查询默认排班
		SchedulWeekExample swExample = new SchedulWeekExample();
		swExample.createCriteria().andIsDefaultEqualTo(1);
		List<SchedulWeek> swList = schedulWeekDao.selectByExample(swExample);
		Integer defaultSwId = swList.get(0).getSwId();
		
		EmployeeSchedulExample esExample = new EmployeeSchedulExample();
		esExample.createCriteria().andEmployeeIdEqualTo(employeeId)
		.andSwIdEqualTo(defaultSwId);
		EmployeeSchedul employeeSchedul = new EmployeeSchedul();
		//employeeSchedul thruDate
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		cal.set(9999, 0, 1);
		Date thruDate = cal.getTime();
		employeeSchedul.setThruDate(thruDate);//9999-01-01
		record = employeeSchedulDao.updateByExampleSelective(employeeSchedul, esExample);
		if (record <= 0) {
			return false;
		}
		
		//删除考勤信息--无法恢复
		
		//恢复结束时间为lastDate的公司、部门、岗位信息，把结束时间设置为null，
		//公司
		EmployeeCorporationExample ecExample = new EmployeeCorporationExample();
		ecExample.or().andEmployeeIdEqualTo(employeeId)
		.andThruDateEqualTo(lastDate);
		List<EmployeeCorporation> ecList = employeeCorporationDao.selectByExample(ecExample);
		for (EmployeeCorporation employeeCorporation : ecList) {
			employeeCorporation.setThruDate(null);
			record = employeeCorporationDao.updateByPrimaryKey(employeeCorporation);
			if (record <= 0) {
				return false;
			}
		}
		//部门
		EmployeeDepartmentExample edExample = new EmployeeDepartmentExample();
		edExample.or().andEmployeeIdEqualTo(employeeId)
		.andThruDateEqualTo(lastDate);
		List<EmployeeDepartment> edList = employeeDepartmentDao.selectByExample(edExample);
		for (EmployeeDepartment employeeDepartment : edList) {
			employeeDepartment.setThruDate(null);
			record = employeeDepartmentDao.updateByPrimaryKey(employeeDepartment);
			if (record <= 0) {
				return false;
			}
		}
		//岗位
		EmployeeRoleExample erExample = new EmployeeRoleExample();
		erExample.or().andEmployeeIdEqualTo(employeeId)
		.andThruDateEqualTo(lastDate);
		List<EmployeeRole> erList = employeeRoleDao.selectByExample(erExample);
		for (EmployeeRole employeeRole : erList) {
			employeeRole.setThruDate(null);
			record = employeeRoleDao.updateByPrimaryKey(employeeRole);
			if (record <= 0) {
				return false;
			}
		}
		//更新撤回离职人员的报表数据的离职日期--null
		attendanceReportExtDao.updateSeparatedDate(employeeId);
		
		//插入任务表数据
		Date nowDay = new Date();
		while (nowDay.after(lastDate)) {
			//判断，插入数据
			approvalService.insertTaskByParam(nowDay, employeeId);
			
			nowDay = DateUtils.addDays(nowDay, -1);
		}
		return true;
	}

}
